import pandas as pd
import matplotlib.pyplot as plt
import pyecharts.options as opts
from pyecharts.charts import Bar, Pie, Map, Line
def read_csv_file(file_path):
    data = []
    with open(file_path, 'r', encoding='utf-8-sig') as file:
        for line in file:
            try:
                # 处理每一行数据
                data.append(line.strip().split(','))
            except Exception as e:
                print(f"Error processing line: {line}")
                print(e)
    return pd.DataFrame(data, columns=['name', 'userid', 'age', 'gender', 'city', 'text', 'comment', 'commentid', 'praise', 'date'])

# 读取数据
df = read_csv_file('music_comments.csv')

# 根据评论ID去重
df = df.drop_duplicates('commentid')

# 检查年龄数据分布
df['age'] = pd.to_numeric(df['age'], errors='coerce')
print(df['age'].describe())

# 处理年龄为0的数据
df['age'] = df['age'].apply(lambda x: '未知' if x == 0 else x)

# 年龄分布图
age_message = df[df['age'] != '未知'].groupby(['age']).size().reset_index(name='count')
bar = (
    Bar()
    .add_xaxis(age_message['age'].tolist())
    .add_yaxis("评论数", age_message['count'].tolist())
    .set_global_opts(title_opts=opts.TitleOpts(title="热门歌曲评论用户的年龄分布", pos_left='center', pos_top='18'))
)
bar.render("热门歌曲评论用户的年龄分布.html")

# 检查性别数据分布
df['gender'] = pd.to_numeric(df['gender'], errors='coerce')
print(df['gender'].value_counts())

# 处理性别数据
df['gender'] = df['gender'].map({1: '男', 2: '女'}).fillna('未知')

# 性别分布图
gender_message = df[df['gender'] != '未知'].groupby(['gender']).size().reset_index(name='count')
pie = (
    Pie()
    .add("", [list(z) for z in zip(gender_message['gender'], gender_message['count'])], radius=[40, 75])
    .set_global_opts(title_opts=opts.TitleOpts(title="热门歌曲评论用户的性别情况", pos_left='center', pos_top=0),
                     legend_opts=opts.LegendOpts(orient="vertical", pos_left="left", pos_top="20%"))
)
pie.render("热门歌曲评论用户的性别情况.html")

# 检查评论日期数据
df['date'] = pd.to_datetime(df['date'], errors='coerce')
print(df['date'].describe())

# 评论日期分布图
date_message = df.groupby(df['date'].dt.date).size().reset_index(name='count')
line = (
    Line()
    .add_xaxis(date_message['date'].astype(str).tolist())
    .add_yaxis("评论数", date_message['count'].tolist(), is_smooth=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.3))
    .set_global_opts(title_opts=opts.TitleOpts(title="歌曲发布后评论的日期分布", pos_left='center', pos_top='22'))
)
line.render("热门歌曲评论的日期分布.html")